/**
 * 
 */
package ua.at.tsvetkov.samizdat.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import ua.at.tsvetkov.strings.Util;
import ua.at.tsvetkov.util.Log;

/**
 * @author A.Tsvetkov 2011, http://tsvetkov.at.ua, al@ukr.net
 */
public class DataFavoriteBooks {

	public LoadedAuthorBooks	authorData;
	public String[]				booksData;
	private String					path;

	/**
	 * Загружает данные по загруженному автору
	 */
	public DataFavoriteBooks(String path) {
		this.path = path;
	}

	/**
	 * Загрузка данных
	 */
	public void load() {
		File dir = new File(path);
		String[] books = dir.list();
		int hiddenCount = 0;
		for (int i = 0; i < books.length; i++) {
			if (books[i].startsWith(".")) {
				hiddenCount++;
			}
		}
		String[] files = new String[books.length - hiddenCount];
		booksData = new String[books.length - hiddenCount];
		int k = 0;
		for (int i = 0; i < books.length; i++) {
			if (!books[i].startsWith(".")) {
				files[k] = books[i];
				booksData[k] = readBookInfo(path + files[k]);
				k++;
			}
		}
		authorData = new LoadedAuthorBooks(path, files);
	}

	/**
	 * Чтение заголовка информации о книге
	 * 
	 * @param fileName
	 * @return
	 */
	private String readBookInfo(String fileName) {
		String infoString = "";
		File file = new File(fileName);
		if (!file.exists() || file.length() == 0) {
			return "";
		}
		BufferedReader in = null;
		try {
			in = new BufferedReader(new FileReader(file));
			infoString = in.readLine();
		} catch (Exception e) {
			Log.e("Error loading file " + fileName, e);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				Log.e("Error loading file " + fileName, e);
			}
		}
		return infoString;
	}

	public Book getBookData(int pos) {
		// [А К М, Лисья анкета, Статья, 6k, 17/12/2002, 7.16, 34, http://samlib.ru/cgi-bin/areader?q=book&object=/a/akm/anketa]
		Book book = new Book();
		String[] data = Util.split(booksData[pos], '|');
		String stObject = data[Data.HEADER_URL];
		book.object = stObject.substring(stObject.indexOf("object=") + 7);
		book.author = data[Data.HEADER_TITLE];
		book.title = data[Data.HEADER_AUTHOR];
		book.type = data[Data.HEADER_TYPE];
		book.size = data[Data.HEADER_SIZE];
		book.date = data[Data.HEADER_DATE];
		book.ball = data[Data.HEADER_BALL];
		book.counter = data[Data.HEADER_COUNTER];
		return book;
	}
}
